<template>
  <section>
    <!-- 面包屑 -->
 <breadcrumbs></breadcrumbs>
    <!-- 查询条件 -->
    <el-form ref="searchForm"
             :model="searchForm"
             label-width="100px"
             inline
             class="demo-form-inline"
             size='small'
             style="border-bottom: 1px solid #f6f6f6;">
      <el-form-item label="角色名称"
                    prop="name">
        <el-input v-model="searchForm.name"
                  placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="search">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <btns @exec="exec"></btns>
    <div class="data-container scroll-table">
      <div>
        <div class="ind-title lh50 f16">角色列表</div>
      </div>
      <!-- 角色列表 -->
      <el-table :data="tableData"
                border
                style="width: 100%"
                @selection-change="tableSelectionChange">
        <el-table-column type="selection"
                         width="40">
        </el-table-column>
        <el-table-column prop="roleName"
                         label="角色名称">
        </el-table-column>
        <el-table-column prop="status"
                         label="状态">
          <template slot-scope="scope">
            <div v-if="scope.row.status==0"
                     type="danger"
                     :underline="false">禁用</div>
            <div v-if="scope.row.status==1"
                     :underline="false">启用</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--新增修改界面-->
    <el-dialog :title="funTit=='add'?'新增':'修改'"
               :visible.sync="addORUpdateVisible"
               width="700px"
               :close-on-click-modal="false">
      <el-form :model="roleForm"
               label-width="80px"
               :rules="rules"
               ref="roleForm">
        <el-form-item label="角色名称"
                      prop="roleName">
          <el-input v-model="roleForm.roleName"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="权限"
                      prop="menuBtn">
          <el-input placeholder="输入关键字进行过滤"
                    v-model="filterTree"></el-input>
          <el-tree :filter-node-method="filterNode"
                   ref="tree"
                   :data="menulistTreeData"
                   show-checkbox
                   :check-strictly="false"
                   :default-expand-all="true"
                   node-key="key"
                   :default-checked-keys="[]"
                   :props="{label:'menuName',children:'children',disabled:'disabled'}"> </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click.native="addORUpdateVisible = false">取消</el-button>
        <el-button type="primary"
                   @click.native="submit('roleForm')">提交</el-button>
      </div>
    </el-dialog>
    <!--接口权限界面-->
    <el-dialog title="设置接口权限"
               :visible.sync="ifVisible"
               width="700px"
               :close-on-click-modal="false">
      <div class="data-container scroll-table">
        <el-table ref="ifTable"
                  @select="select"
                  @select-all="selectAll"
                  :data="ifData"
                  style="width: 100%"
                  row-key="ifId"
                  border
                  lazy
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  @selection-change="ifTableChange">
          <el-table-column type="selection"
                           width="40">
          </el-table-column>
          <el-table-column prop="ifName"
                           label="名称"
                           width="200">
          </el-table-column>
          <el-table-column prop="ifDs"
                           label="描述"
                           width="200">
          </el-table-column>
          <el-table-column prop="ifUrl"
                           label="路径">
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click.native="ifVisible = false">取消</el-button>
        <el-button type="primary"
                   @click.native="setInterFace">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

import btns from '@/components/btns.vue'
import breadcrumbs from "@/components/breadcrumbs.vue";
export default {
  components: {
    btns,
    breadcrumbs,
  },
  data () {
    return {
      user: this.$store.state.user,
      searchForm: {
        name: ''
      },
      addORUpdateVisible: false,
      funTit: '',
      filterTree: '',
      roleForm: {
        "menuBtn": {},
        "roleName": "",
      },
      rules: {
        "roleName": [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      tableData: [],
      tableSelection: [],
      menulistData: [],
      menulistTreeData: [],
      btnlistData: [],
      menuTableSelection: [],
      ifData: [],
      ifDataAll: [],
      ifVisible: false,
      ifTableSelection: [],
      stoke: true
    }
  },
  created () {
    this.rolelist();
    this.btnlist();
    this.iflist();
    console.log(this.user)
  }, watch: {
    filterTree (val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    selectAll (v) {
      this.stoke = false;
      if (v.filter(e => e.ifPid == 0).length > 0) {
        v.filter(e => e.ifPid == 0).forEach(e => {
          e.children.forEach(c => {
            this.$refs.ifTable.toggleRowSelection(c, true);
          })
        })
      } else {
        this.ifData.forEach(e => {
          e.children.forEach(c => {
            this.$refs.ifTable.toggleRowSelection(c, false);
          })
        })
      }
    },
    select (row, r) {
      if (r.ifPid == 0) {
        this.stoke = false;
        var isadd = this.ifTableSelection.findIndex(e => e.ifId == r.ifId) < 0;
        r.children.forEach(c => {
          this.$refs.ifTable.toggleRowSelection(c, isadd);
        })
        return
      }
      this.stoke = true;
    },
    ifTableChange (val) {
      this.ifTableSelection = val;
      if (this.stoke) {
        this.stoke = false;
        // console.log(val);
        var selre = this.ifTableSelection.filter(e => e.ifPid > 0);
        var pp = [];
        var no = [];
        selre.forEach(e => {
          this.$refs.ifTable.toggleRowSelection(e, true);
          this.ifDataAll.forEach(a => {
            if (a.ifPid > 0 && selre.findIndex(b => b.ifId == a.ifId) < 0) {
              no.push(a);
            }
          })
          var p = this.ifData.find(p => p.ifId == e.ifPid);
          if (selre.filter(a => a.ifPid == p.ifId).length == p.children.length) {
            //
            this.$refs.ifTable.toggleRowSelection(p, true);
          } else {
            this.$refs.ifTable.toggleRowSelection(p, false);
          }
        })
        no.forEach(e => {
          this.$refs.ifTable.toggleRowSelection(e, false);
        })
      }
    },
    iflist () {
      //获取接口
      this.$api.system.iflist({}).then(d => {
        if (d.code == 200) {
          this.ifDataAll = d.data;
          this.getiflist(d.data);
        }
      }).catch((e) => {
        console.log(e);
      })
    },
    getiflist (nowdata) {
      // console.log(111111, nowdata);
      var data = nowdata ? nowdata.filter(e => e.ifPid == 0) : [];
      var temp = [];
      // console.log(111111, nowdata);
      data.forEach(e => {
        e.ifDs = e.ifDs ? e.ifDs.replace(/ /g, '').replace('Controller', '').toLowerCase() : e.ifDs;

        e.children = nowdata.filter(c => c.ifPid == e.ifId);
        if (e.children && e.children.length > 0) {
          temp.push(e)
        }
      })
      this.ifData = temp;
    },
    btnlist () {
      //获取接口
      this.$api.system.btnlist({}).then(d => {
        if (d.code == 200) {
          d.data.forEach(e => {
            e.btnId = e.btnId + '';
          })
          this.btnlistData = d.data;
          this.menulist();
        } else {
          this.$message.error(d.msg);
        }
      }).catch((e) => {
        console.log(e);
      })
    },
    menulist () {
      //获取接口
      this.$api.system.menulist({}).then(d => {
        if (d.code == 200) {

          var menus = []
          this.$store.state.menu.forEach(c => {
            menus.push(c)
            c.children.forEach(a => {
              menus.push(a)
            })
          })
          var r = [];
          d.data.forEach(e => {
            r.push(e);
            if (menus.findIndex(c => c.menuId == e.menuId) >= 0) {
              r.push(e);
            }
          })
          // console.log(111111111111111111, d.data);
          this.menulistData = d.data;
          this.getdata(this.menulistData);
          // console.log(11231, this.menulistData);
        } else {
          this.$message.error(d.msg);
        }
      }).catch((e) => {
        console.log(e);
      })
    },
    getdata (nowdata, isde) {// tree 数据组装
      var data = nowdata.filter(e => e.pid == 0);
      var temp = [];
      data.forEach(e => {
        e.children = nowdata.filter(c => c.pid == e.menuId);
        // console.log(1111, e);
        e.disabled = e.status == 0
        e.type = 'menu';
        e.key = 'menu' + e.menuId;
        if (e.children && e.children.length > 0) {
          e.children.forEach(c => {
            c.disabled = c.status == 0
            c.deep = 1;
            c.type = 'menu';
            c.key = 'menu' + c.menuId;
            c.children = [{
              type: 'btn',
              key: c.menuId + 'btn_' + c.menuId,
              pid: c.menuId,
              menuName: '查看',
              menuId: '',
            }];
            if (!isde) {
              c.btnIds = c.btnIds ? c.btnIds.split(',') : [];
              c.btnIds.forEach(b => {
                var btn = this.btnlistData.find(r => r.btnId == b);
                if (btn) {
                  c.children.push({
                    disabled: btn.status == 0,
                    type: 'btn',
                    key: c.menuId + 'btn' + btn.btnId,
                    pid: c.menuId,
                    menuName: btn.btnName,
                    menuId: btn.btnId,
                  })
                }
              })
            }
          })
        }
        if (!isde) {
          e.btnIds = e.btnIds ? e.btnIds.split(',') : [];
          e.btnIds.forEach(b => {
            var btn = this.btnlistData.find(r => r.btnId == b);
            if (btn) {
              e.children.push({
                disabled: btn.status == 0,
                type: 'btn',
                key: e.menuId + 'btn' + btn.btnId,
                pid: e.menuId,
                menuName: btn.btnName,
                menuId: btn.btnId,
              })
            }
          })
        }
        temp.push(e);
      })
      // console.log(temp);
      this.menulistTreeData = temp;
    },
    filterNode (value, data) {
      if (!value) return true;
      return data.menuName.indexOf(value) !== -1;
    },
    menuTableSelectionChange (val, v) {
      this.menuTableSelection = val;
    },
    handleReset () {
      this.$refs.searchForm.resetFields();
      this.search()
    },
    search () {
      if (this.searchForm.name) {
        this.$api.role.list({
          roleName: this.searchForm.name.trim()
        }).then(d => {
          if (d.code == 200) {
            this.tableData = d.data;
          }
        })
      } else {
        this.rolelist();
      }
    },
    rolelist () {
      //获取接口
      this.$api.role.list({}).then(d => {
        if (d.code == 200) {
          this.tableData = d.data;
        } else {
          this.$message.error(d.msg);
        }
      }).catch((e) => {
        console.log(e);
      })
    },
    tableSelectionChange (val) {
      this.tableSelection = val;
    },
    exec (fun) {
      if (this[fun]) {
        this.funTit = fun;
        this[fun]()
      } else {
        this.$message.error('方法未定义');
      }
    },
    add () {
      this.roleForm = {
        "menuBtn": {},
        "roleName": "",
      }
      this.filterTree = ''
      this.addORUpdateVisible = true;
      this.$nextTick(e => {
        this.$refs.tree.setCheckedKeys([]);
        //this.$refs.tree.setCheckedKeys([3])
      })
    },
    update () {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }

      this.roleForm = this.tableSelection[0];
      this.filterTree = ''
      //获取接口
      this.$api.role.info({ roleId: this.roleForm.roleId }).then(d => {
        if (d.code == 200) {
          this.addORUpdateVisible = true;
          this.$nextTick(e => {
            var keys = [];
            for (var key in d.data.ifMap) {
              if (d.data.ifMap[key].menuInfo) {
                var menuBtnList = d.data.ifMap[key].menuBtnList;
                if (!menuBtnList || menuBtnList && menuBtnList.length == 0) {
                  keys.push(key + 'btn_' + key);
                } else {
                  var btnIds = [];
                  menuBtnList.forEach(e => {
                    keys.push(key + 'btn' + e.btnId);
                    btnIds.join(e.btnId);
                  })
                  if (this.menulistData.findIndex(e => e.btnIds == btnIds.join(',')) >= 0)
                    keys.push(key + 'btn_' + key);
                }
              }
            }
            this.$refs.tree.setCheckedKeys(keys)
          })
        } else {
          this.$message.error(d.msg);
        }
      }).catch((e) => {
        console.log(e);
      })
    },
    del () {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }

      let role = this.tableSelection[0];
      console.log('role', role);
      if (role.status == 1) {
        this.$message.error('该角色已启用');
        return
      }
      if (role.roleId == 1) {
        this.$message.error('不能删除超级管理员');
        return
      }
      if (role.roleId == 2) {
        this.$message.error('不能删除商户用户');
        return
      }
      this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.role.deleteRole({
          roleId: role.roleId
        }).then(d => {
          if (d.code == 200) {
            this.$message.success('删除成功')
            this.rolelist();
          } else {
            this.$message.error(d.msg)
          }
        }).catch(e => {
          console.log(e)
        })
      });

    },
    refresh () {
      this.rolelist();
    },
    enable () {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }
      var demo = this.tableSelection[0];
      if (demo.status == 1) {
        this.$message.error('该数据已启用');
        return
      }
      this.$confirm('此操作将启用该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.role.updateStatus({ roleId: demo.roleId, status: 1 }).then(d => {
          if (d.code == 200) {
            this.rolelist();
            this.$message.success('启用成功');
          } else {
            this.$message.error(d.msg);
          }
        }).catch((e) => {
          console.log(e);
        })
      });
    },
    disable () {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }
      var demo = this.tableSelection[0];
      if (demo.status == 0) {
        this.$message.error('该数据已禁用');
        return
      }
      this.$confirm('此操作将禁用该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.role.updateStatus({ roleId: demo.roleId, status: 0 }).then(d => {
          if (d.code == 200) {
            this.rolelist();
            this.$message.success('禁用成功');
          } else {
            this.$message.error(d.msg);
          }
        }).catch((e) => {
          console.log(e);
        })
      });
    },
    interface () {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }
      this.roleForm = this.tableSelection[0];
      this.ifVisible = true;
      var ifIds = this.roleForm.ifIds.split(',');
      this.stoke = false;
      this.$nextTick(e => {
        this.ifData.forEach(e => {
          if (ifIds.indexOf(e.ifId + '') >= 0) {
            this.$refs.ifTable.toggleRowSelection(e, true);
          }
          e.children.forEach(c => {
            if (ifIds.indexOf(c.ifId + '') >= 0) {
              this.$refs.ifTable.toggleRowSelection(c, true);
            }
          })
        })
      })
    },
    setInterFace () {
      var ifIds = [];
      this.ifTableSelection.forEach(e => {
        ifIds.push(e.ifId)
      })
      this.roleForm.ifIds = ifIds.join(',');
      console.log(1111111, this.roleForm.ifIds);
      this.$api.role.updateIf(this.roleForm).then(d => {
        if (d.code == 200) {
          this.$message.success('设置成功');
          this.ifVisible = false;
          this.rolelist();
        } else {
          this.$message.error(d.msg);
        }
      }).catch((e) => {
        console.log(e);
      })
    },
    getMenuBtn () {
      var tree = this.$refs.tree.getCheckedNodes();

      var menuBtn = {};
      var menubtn = tree.filter(e => e.type == 'btn');
      menubtn.forEach(e => {
        if (!menuBtn[e.pid]) {
          var btns = [];
          menubtn.forEach(b => {
            if (b.pid == e.pid && b.menuId) {
              btns.push(b.menuId);
            }
          });
          menuBtn[e.pid] = btns.join(',');
        }
      })
      return menuBtn;
    },
    submit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.roleForm.menuBtn = this.getMenuBtn();
          // console.log(this.roleForm.menuBtn);
          // console.log(this.roleForm);
          // this.roleForm.ifIds = this.roleForm.menuBtn;
          if (this.funTit == 'add') {
            this.$api.role.add(this.roleForm).then(d => {
              if (d.code == 200) {
                this.addORUpdateVisible = false;
                this.$refs.roleForm.resetFields();
                this.rolelist();
              } else {
                this.$message.error(d.msg);
              }
            }).catch((e) => {
              console.log(e);
            })
          } else {
            // console.log(111111111, this.roleForm);
            this.$api.role.update(this.roleForm).then(d => {
              if (d.code == 200) {
                this.addORUpdateVisible = false;
                this.$refs.roleForm.resetFields();
                this.$message.success('设置成功');
                this.rolelist();
              } else {
                this.$message.error(d.msg);
              }
            }).catch((e) => {
              console.log(e);
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}

</script>